﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Q_SMS.Response;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Q_SMS.Sender
{
    class SMSMultiSender
    {
        const string url = "https://yun.tim.qq.com/v5/tlssmssvr/sendmultisms2";
        public static SMSMultiResult Send(string appid, string appkey, int type, string nationCode, List<string> phoneNumbers, string msg, string extend, string ext, string sign, string templateId, IList<string> parms)
        {
            long random = Tools.GetRandom();
            long curTime = Tools.GetCurTime();

            // 按照协议组织 post 请求包体
            JObject data = new JObject();
            data.Add("tel", Tools.PhoneNumbersToJSONArray(nationCode, phoneNumbers));

            data.Add("sig", Tools.CalculateSig(appkey, random, curTime, phoneNumbers));
            if (type != -1)
            {
                data.Add("type", type);
                data.Add("msg", msg);
            }
            else
            {
                data.Add("params", Tools.ParmsToJSONArray(parms));
                data.Add("tpl_id", templateId);
                data.Add("sign", sign);
            }
            data.Add("time", curTime);
            data.Add("extend", extend);
            data.Add("ext", ext);

            string wholeUrl = url + "?sdkappid=" + appid + "&random=" + random;
            HttpWebRequest request = Tools.GetPostHttp(wholeUrl);
            byte[] requestData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
            request.ContentLength = requestData.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(requestData, 0, requestData.Length);
            requestStream.Close();

            // 接收返回包
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            string responseStr = streamReader.ReadToEnd();
            streamReader.Close();
            responseStream.Close();
            SMSMultiResult result;
            if (HttpStatusCode.OK == response.StatusCode)
            {
                result = JsonConvert.DeserializeObject<SMSMultiResult>(responseStr);
            }
            else
            {
                result = new SMSMultiResult();
                result.Result = -1;
                result.Errmsg = "http error " + response.StatusCode + " " + responseStr;
            }
            return result;
        }
    }
}
